package cn.ehanghai.htz.thread;


import cn.ehanghai.htz.client.TcpClient;
import cn.ehanghai.htz.common.utils.AisUtil;
import cn.ehanghai.htz.common.utils.ApplicationContextUtil;
import cn.ehanghai.htz.domain.ServiceInfo;
import cn.ehanghai.htz.service.PositionService;
import cn.ehanghai.htz.service.ServiceInfoService;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;


/**
 * @Author: xumf
 * @Date: 2019/7/5 10:29
 */
@Slf4j
public class TcpClientReadAisThread extends Thread{

    private ServiceInfoService serviceInfoService= (ServiceInfoService) ApplicationContextUtil.getBean(ServiceInfoService.class);

//    private boolean socketFlag=false;
    @Override
    public void run() {
        log.warn("开启TCPClient读取ais数据线程-----");
        ServiceInfo serviceInfo;
        while (true){
            try {
                serviceInfo=serviceInfoService.select();
                if(serviceInfo!=null){
//                    serviceInfo.setServerIp("192.168.20.39");
                    serviceInfo.setServerIp("202.118.80.110");
                    serviceInfo.setPort(8888);
                    Socket socket= TcpClient.getInstance(serviceInfo.getServerIp(), serviceInfo.getPort());
                    if(socket!=null){
                        readMessageFromServer(socket);
                        //todo 判断socket server 是否关闭
                    }
                    else{
                        System.out.println("----正在连接。。。请稍等----");
                    }
                }
                log.warn("-----睡眠5秒------");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void readMessageFromServer(Socket socket){
        try {
            InputStream is=socket.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            String info=null;
            int count=0;
            while ((info=br.readLine())!=null&&TcpClient.getReadFlag()){
                log.warn("接受服务器数据第{}：",count+"条信息内容--{}",info);
                AisUtil.parsingAis(info);
                count++;
            }
        } catch (IOException e) {
//            e.printStackTrace();
            log.error("---socket出错了----");
            TcpClient.setSocket(null);

        }
    }
}
